package com.hevery.blog.controller;

import com.hevery.blog.model.TestVO;
import com.hevery.blog.common.annotation.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.sql.DataSource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: Controller
 * @author: hongyu.zhang
 * @create: 2018-03-28
 **/
@Controller
public class WelComeController {

    @Autowired
    private DataSource dataSource;
    @RequestMapping(value = {"/index"})
    @ResponseBody
    public String hello(){
        return "index";
    }

    @RequestMapping("/")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("first");
        mv.addObject("user","hevery");
        return mv;
    }

    @RequestMapping("/test")
    public String index2(Model model){
        model.addAttribute("user","hevery");
        return "first";
    }
    @GetMapping("/testDruid")
    @ResponseBody
    public String testDruid(){
        return "testDruid";
    }

    @RequestMapping(value = {"/hello"})
    @ResponseBody
    public Map<String,Object> hello2(String a,String b){
        Map<String,Object> map = new HashMap<>();
        map.put("a",a);
        map.put("b",b);
        return map;
    }
    @RequestMapping(value = {"/hello3"})
    @ResponseBody
    public Map<String,Object> hello3(@RequestBody Map<String,Object> map){
        return map;
    }

    @RequestMapping("/validator")
    @ResponseBody
    public String validator(@Valid TestVO testVO, BindingResult result){
        if(result.hasErrors()){
            return result.getAllErrors().get(0).getDefaultMessage();
        }
        return "validator";
    }
    @RequestMapping("/exception")
    @ResponseBody
    public String testException(){
        int i = 1/0;
        return "exception";
    }

    @RequestMapping("/security")
    @ResponseBody
    @Security
    public String testSecurity(){
        return "security";
    }
}
